package co.fitstart.admin.web.controller.user;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.demo2do.core.support.Page;
import com.demo2do.core.support.Result;
import com.demo2do.core.utils.CollectionUtils;
import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.demo2do.core.web.resolver.Preloading;

import co.fitstart.admin.entity.security.Login;
import co.fitstart.admin.service.DataService;
import co.fitstart.admin.web.interceptor.MenuSetting;
import co.fitstart.admin.web.resolver.Secure;
import co.fitstart.entity.site.Site;
import co.fitstart.entity.user.UserSourceType;

/**
 * 
 * @author mohanlan
 *
 */
@Controller
@RequestMapping("/source-channels")
@MenuSetting("menu-source")
public class SourceChannelController {

	private static final Logger logger = LoggerFactory.getLogger(SourceCreateController.class);

	@Autowired
	@Qualifier("dataService")
	private DataService<UserSourceType> sourceChannelService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	@MenuSetting("submenu-source-management")
	public ModelAndView createSearch(@Secure Login login, HttpServletRequest request, Page page) {

		ModelAndView modelAndView = new ModelAndView("source/source-channel-list");
		
		Site site = null;
        if (login.hasSite()){
            site = login.getSite();
        }
        
        if(site != null) {
        	
        	List<UserSourceType> sources = sourceChannelService.listAll(UserSourceType.class);
            
    		List<UserSourceType> parent = new ArrayList<UserSourceType>();
    		List<UserSourceType> children = new ArrayList<UserSourceType>();
    		
    		for(UserSourceType sourceType : sources) {
    			if(sourceType.getParent() != null) {
    				if(!StringUtils.isEmpty(sourceType.getSites()) && sourceType.getSites().contains(site.getCode())) {
    					children.add(sourceType);
    				} else {
    					children.add(sourceType);
    				}
    			} else {
    				if(!StringUtils.isEmpty(sourceType.getSites()) && sourceType.getSites().contains(site.getCode())) {
    					parent.add(sourceType);
    				} else {
    					parent.add(sourceType);
    				}
    			}
    		}
    		
    		Map<String, UserSourceType> parentMap = CollectionUtils.constructMapValueFromList(parent, "id");
    		modelAndView.addObject("parentMap", parentMap);
    		
    		
    		Map<String, List<UserSourceType>> childrensMap = CollectionUtils.constructMapValuesFromList(children, "parent");
    		modelAndView.addObject("childrensMap", childrensMap);
    		
    		return modelAndView;
        	
        } else {
        	
        	List<UserSourceType> sources = sourceChannelService.listAll(UserSourceType.class);
            
    		List<UserSourceType> parent = new ArrayList<UserSourceType>();
    		List<UserSourceType> children = new ArrayList<UserSourceType>();
    		for(UserSourceType sourceType : sources) {
    			if(sourceType.getParent() != null) {
    				children.add(sourceType);
    			} else {
    				parent.add(sourceType);
    			}
    		}
    		
    		Map<String, UserSourceType> parentMap = CollectionUtils.constructMapValueFromList(parent, "id");
    		modelAndView.addObject("parentMap", parentMap);
    		
    		
    		Map<String, List<UserSourceType>> childrensMap = CollectionUtils.constructMapValuesFromList(children, "parent");
    		modelAndView.addObject("childrensMap", childrensMap);
    		
    		return modelAndView;
        }
		
		
	}
	
	 /**
     * View create panel
     * 
     * @param type
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView create(@RequestParam(value = "parent") Long type) {
        
        ModelAndView modelAndView = new ModelAndView("source/source-channel-create");
        
        modelAndView.addObject("parent", type);
        
        UserSourceType parentType = sourceChannelService.load(UserSourceType.class, type);
        
        modelAndView.addObject("parent", type);
        modelAndView.addObject("parentType", parentType);
        
        return modelAndView;
    }
    
    /**
     * On create product category
     * 
     * @param productCategory
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.POST)
    public @ResponseBody String onCreate(UserSourceType userSourceType) {
        
        Result result = new Result();
        
        try {
            
            sourceChannelService.save(userSourceType);
            
            result.success().message("创建渠道二级分类成功！");
            
        } catch(Exception e) {
            
            logger.error("#onCreate() - ", e);
            
            result.fail().message("创建渠道二级分类失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
    }
    
    /**
     * View category edit panel
     * 
     * @param productCategoryId
     * @return
     */
    @RequestMapping(value = "/{sourceId}/edit", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("sourceId") Long sourceId) {
        
        ModelAndView modelAndView = new ModelAndView("source/source-channel-edit");
        
        UserSourceType userSourceType = sourceChannelService.load(UserSourceType.class, sourceId);
        
        modelAndView.addObject("userSourceType", userSourceType);
        
        return modelAndView;
    }

    /**
     * Do edit product category
     * 
     * @param productCategory
     * @param cover
     * @return
     */
    @RequestMapping(value = "/{sourceId}", method = RequestMethod.PATCH)
    public @ResponseBody String onEdit(@Preloading("sourceId") UserSourceType userSourceType) {
        
        Result result = new Result();
        
        try {
            
            sourceChannelService.update(userSourceType);
            
            result.success().message("修改渠道二级分类成功！");
            
        } catch(Exception e) {
            
            logger.error("#onEdit() - ", e);
            
            result.fail().message("修改渠道二级分类失败！");
            
        }
        
        return JsonUtils.toJsonString(result);
        
    }

}
